package com.mlink.ai.chat.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.FragmentExploreBinding
import com.mlink.ai.chat.bean.ExploreCategory
import com.mlink.ai.chat.bean.ExploreSubCategory
import com.mlink.ai.chat.constants.isCreateNewPrompt
import com.mlink.ai.chat.ui.viewmodel.ExploreViewModel
import com.mlink.ai.chat.utils.AnalyticsEvents
import com.mlink.ai.chat.utils.AnalyticsParams
import com.mlink.ai.chat.utils.PromptUtils
import com.mlink.ai.chat.utils.logEvent

class ExploreFragment : BaseFragment<FragmentExploreBinding>(), OnTabSelectedListener {

    private var categoryList = ArrayList<ExploreCategory>()

    private var isTriggerByListSeeAll = false
    private var selectedCategoryId : Long? = null
    var deleteView: View? = null
    companion object {
        fun newInstance() = ExploreFragment()
    }

    private val viewModel: ExploreViewModel by lazy {
        ViewModelProvider(requireActivity())[ExploreViewModel::class.java]
    }

    override fun getViewBinding(): FragmentExploreBinding {
        return FragmentExploreBinding.inflate(LayoutInflater.from(context))
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        context?.let {
            viewModel.getAllCategory(it)
        }

        viewModel.categoriesLiveDada.observe(this.viewLifecycleOwner) {
            categoryList.clear()
            categoryList.addAll(it)
            createCategoriesTab(it)
            addCreateCategory(it)
        }
        binding.tabLayout.addOnTabSelectedListener(this)
    }

    override fun onResume() {
        super.onResume()
        if (isCreateNewPrompt) {
            isCreateNewPrompt = false
            viewModel.getAllCategory(requireContext())
        }
    }

    override fun onDestroyView() {
        binding.tabLayout.removeOnTabSelectedListener(this)
        super.onDestroyView()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) {
            deleteView?.isVisible = false
        }
        super.onHiddenChanged(hidden)
    }

    override fun onStop() {
        deleteView?.isVisible = false
        deleteView = null
        super.onStop()
    }

    private fun createCategoriesTab(categoryList: List<ExploreCategory>) {
        val list = ArrayList<String>()
        list.add(resources.getString(R.string.explore_category_all))
        for (category in categoryList) {
            category.categoryName?.let {
                list.add(it)
            }
        }
        binding.tabLayout.removeAllTabs()
        for (category in list) {
            val tabItemView = layoutInflater.inflate(R.layout.explore_tab_item, null)
            val tabTitle = tabItemView.findViewById<TextView>(R.id.tab_title)
            tabTitle.text = category
            binding.tabLayout.addTab(binding.tabLayout.newTab().setCustomView(tabItemView),false)
        }
        // 恢复 tab 选中
        selectedCategoryId?.let {
            for (i in categoryList.indices) {
                if (categoryList[i].id == selectedCategoryId) {
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(i + 1))
                    return
                }
            }
        }
        // 默认第一项
        binding.tabLayout.selectTab(binding.tabLayout.getTabAt(0))
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        val position = tab?.position ?: 0
        if (position == 0) {
            selectedCategoryId = null
        }
        if (categoryList.isNotEmpty() && position in 1..categoryList.size) {
            val category = categoryList[position - 1]
            selectedCategoryId = category.id
        }
        navigationToSelectedFragment(position)
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    private fun navigationToSelectedFragment(position: Int) {
        when (position) {
            0 -> {
                showAllCategoryFragment()
            }
            else -> {
                if (categoryList.isNotEmpty() && position in 1..categoryList.size) {
                    val category = categoryList[position - 1]
                    showCategoryFragment(category)
                }
            }
        }
    }

    private fun showCategoryFragment(category: ExploreCategory) {
        AnalyticsEvents.AC_EXP_PPT_SEEALL_CLICK.logEvent(Bundle().apply {
            var type = "tag"
            if (isTriggerByListSeeAll) {
                type = "list"
                isTriggerByListSeeAll = false
            }
            putString(AnalyticsParams.KEY_LIST_TYPE, type)
            putString(AnalyticsParams.CATEGORY, category.categoryEventName)
            putString(
                AnalyticsParams.KEY_TYPE, if (category.isCustom) {
                    AnalyticsParams.CUSTOM
                } else AnalyticsParams.PRESET
            )
        })
        val fragment = ExploreCategoryFragment.newInstance(category)
        childFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }

    private fun showAllCategoryFragment() {
        val fragment = ExploreAllCategoryFragment.newInstance()
        fragment.setOnSeeAllListener(object : ExploreAllCategoryFragment.OnSeeAllListener {
            override fun onSeeAll(position: Int, category: ExploreCategory) {
                isTriggerByListSeeAll = true
                setCurrentSelectedTab(position + 1)
            }
        })
        childFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }

    private fun setCurrentSelectedTab(position: Int) {
        binding.tabLayout.getTabAt(position)?.select()
    }

    /**
     * 添加创建 Category 的入口
     */
    private fun addCreateCategory(list: List<ExploreCategory>) {
        for (category in list) {
            // 添加创建 Category 的入口
            val createCategory = ExploreSubCategory(PromptUtils.PROMPT_CREATE_ITEM_ID, "")
            (category.subCategories as ArrayList).add(createCategory)
        }
    }
}